import { refreshAuth } from '@/api/login'
import { setToken, removeToken } from '@/utils/auth'

export let isRefreshing = false // 当前是否在请求刷新 Token
let requestQueue = [] // 将在请求刷新 Token 中的请求暂存起来，等刷新 Token 后再重新请求

// 执行暂存起来的请求
const executeQueue = error => {
  requestQueue.forEach(promise => {
    if (error) {
      promise.reject(error)
    } else {
      promise.resolve()
    }
  })

  requestQueue = []
}

const refreshToken = () => {
  // 如果当前是在请求刷新 Token 中，则将期间的请求暂存起来
  if (isRefreshing) {
    return new Promise((resolve, reject) => {
      requestQueue.push({ resolve, reject })
    })
  }

  isRefreshing = true
  return new Promise(resolve => {
    refreshAuth()
      .then(res => {
        const { token, expire } = res.data
        setToken(token, expire)
        isRefreshing = false
        resolve()
        executeQueue(null)
      })
      .catch(() => {
        isRefreshing = false
        removeToken()
      })
      .finally(() => {
        isRefreshing = false
      })
  })
}

export default refreshToken
